
package com.kanjian.music.adapter;

import java.util.ArrayList;

import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.kanjian.music.R;
import com.kanjian.music.activity.BaseActivity;
import com.kanjian.music.api.ApiRequestManager;
import com.kanjian.music.constants.IntentConstants;
import com.kanjian.music.entity.FM;
import com.kanjian.music.fragment.MusicPlayerRadioListFragemnt;

/**
 * 推荐页ListAdapter
 * 
 * @author xuyanjun@kanjian.com
 */
public class SimpleFMListAdapter extends BaseAdapter {

    private BaseActivity mActivity;

    private MusicPlayerRadioListFragemnt mFragment;
    
    private ArrayList<FM> mFMList;

    private LayoutInflater mLayoutInflater;

    public SimpleFMListAdapter(BaseActivity context, ArrayList<FM> fmlist,
            MusicPlayerRadioListFragemnt fragment) {
        this.mActivity = context;
        this.mFMList = fmlist;
        this.mFragment = fragment;
        mLayoutInflater = LayoutInflater.from(mActivity);
    }

    public void registerOnItemClickListener(ListView listView) {
        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                FM fm = (FM) getItem(position);
                mFragment.mCurrentRadioType = fm.mFMId;
                Bundle args = new Bundle();
                args.putSerializable(IntentConstants.HTTPLOADERREQUESTPARAM,
                        ApiRequestManager.getRadioRequest(fm.mFMId));
                mActivity.getSupportLoaderManager().restartLoader(0, args, mFragment);
            }
        });
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null || convertView.getTag() == null) {
            holder = new ViewHolder();
            convertView = mLayoutInflater.inflate(R.layout.item_list_fm_simple, null);
            holder.mTv = (TextView) convertView.findViewById(R.id.item_list_fm_title);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        FM fm = getItem(position);
        holder.mTv.setText(fm.mName);
        return convertView;
    }

    static class ViewHolder {
        TextView mTv;
    }

    @Override
    public int getCount() {
        return mFMList != null ? mFMList.size() : 0;
    }

    @Override
    public FM getItem(int position) {
        return mFMList != null ? mFMList.get(position) : null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

}
